import { Store } from "@/store";
import { utils } from "@/utils";
import { reactive } from "vue";
import { ClientApi } from "@/apis";
import { useRouter } from "vue-router";
import { RouteKey } from "@/router/router";

interface ConfigMenu {
  name: string;
  functionName: string;
  icon: string;
  userType: number[];
}

const configMenus: ConfigMenu[] = [
  {
    name: "退出登录",
    functionName: "logout",
    icon: "logout",
    userType: [utils.enums.UserType.Admin, utils.enums.UserType.Normal]
  }
];

export function useHeader() {
  const store = Store.root();
  const router = useRouter();

  const state = reactive({
    isWindowTop: false,
    menuOptions: configMenus.filter((menu) => menu.userType.includes(store.user.role)) as ConfigMenu[]
  });

  const configMenusFuns: Record<string, Function> = {
    logout: async () => {
      const ok = await utils.Modals.confirm("确认退出登录吗？", { type: "primary", title: "提示" });
      if (!ok) return;
      if (store.isCliteFullScreen) {
        ClientApi.WindowControl({
          command: "max"
        });
      }
      store.$reset();
      sessionStorage.clear();
      router.push(RouteKey.Login);
    }
  };

  // 点击系统菜单
  function clickConfigMenu(menu: ConfigMenu) {
    configMenusFuns[menu.functionName] && configMenusFuns[menu.functionName]();
  }

  async function handleWindowControl(command: DTO.Client.WindowControlParams["command"]) {
    if (command === "close") {
      const ok = await utils.Modals.confirm("确认退出程序吗？", { type: "primary", title: "提示" });
      if (!ok) return;
    }
    ClientApi.WindowControl({
      command: command
    });
  }

  return { state, rootStore: store, clickConfigMenu, handleWindowControl };
}
